package com.atguigu.tingshu.account.receiver;

import com.atguigu.tingshu.account.service.RechargeInfoService;
import com.atguigu.tingshu.account.service.UserAccountService;
import com.atguigu.tingshu.common.constant.KafkaConstant;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.apache.kafka.clients.consumer.ConsumerRecord;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.kafka.annotation.KafkaListener;
import org.springframework.stereotype.Component;

import java.math.BigDecimal;

/**
 * @author ajin
 * @create 2024-10-18 22:39
 */
@Slf4j
@Component
public class AccountReceiver {
    @Autowired
    private UserAccountService userAccountService;

    @Autowired
    private RechargeInfoService rechargeInfoService;

    /**
     * 监听用户充值成功消息
     *
     * @param record
     */
    @KafkaListener(topics = KafkaConstant.QUEUE_RECHARGE_PAY_SUCCESS)
    public void rechargeSuccess(ConsumerRecord<String, String> record) {
        String orderNo = record.value();
        if (StringUtils.isNotBlank(orderNo)) {
            log.info("[账户服务]监听到充值成功消息，订单编号：{}", orderNo);
            rechargeInfoService.rechargeSuccess(orderNo);
        }
    }

    /**
     * 监听信息并添加账户信息
     * @param record
     */
    @KafkaListener(topics = KafkaConstant.QUEUE_USER_REGISTER)
    public void initUserAccount(ConsumerRecord<String,String> record)
    {
        String userId = record.value();
        if (StringUtils.isEmpty(userId)){
            return;
        }
        userAccountService.saveUserAccount(Long.valueOf(userId));
    }

    /**
     * 扣减锁定金额
     *
     * @param record
     */
    @KafkaListener(topics = KafkaConstant.QUEUE_ACCOUNT_MINUS)
    public void minus(ConsumerRecord<String, String> record) {
        String orderNo = record.value();
        if (StringUtils.isNotBlank(orderNo)) {
            log.info("【账户服务】监听到扣减锁定金额消息：{}", orderNo);
            //扣减锁定金额
            userAccountService.minus(orderNo);
        }
    }

    /**
     * 还原锁定金额
     *
     * @param record
     */
    @KafkaListener(topics = KafkaConstant.QUEUE_ACCOUNT_UNLOCK)
    public void unlock(ConsumerRecord<String, String> record) {
        String orderNo = record.value();
        if (StringUtils.isNotBlank(orderNo)) {
            log.info("【账户服务】监听到还原锁定金额消息：{}", orderNo);
            //  调用还原锁定金额
            userAccountService.unlock(orderNo);
        }
    }
}
